package com.zzyl.intercept;

import cn.hutool.core.map.MapUtil;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
@RequiredArgsConstructor
public class UserInterceptor implements HandlerInterceptor {

    private final JwtTokenManagerProperties jwtTokenManagerProperties;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //HandlerMethod代表了controller层中的所有方法,handle代表了执行器
        //这句代码的含义是如只要不是Controller层中的方法都直接放行
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        //获取请求头中的token,authorization
        String token = request.getHeader(Constants.USER_TOKEN);//authorization
        //开始解析token
        log.info("开始获取token的值：{}" + token);

        //判断请求头中的token是否为空
        if (ObjectUtil.isEmpty(token)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

        //解析JWT令牌，获取claims负荷,参数分别为密钥和jwt令牌
        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
        //如果密钥出错，负荷会为空
        if(ObjectUtil.isEmpty(claims)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

        //获取用户的id
        //参数分别代表的是负荷对象，要获得负荷对象中的键名，该键的值的类型
        Long userId = MapUtil.get(claims, Constants.JWT_USERID, Long.class);

        //判断用户id是否为空
        if (ObjectUtil.isEmpty(userId)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

        //将用户的id设置到ThreadLocal中，一个请求就是一个线程，好处是可以三层架构可以不用像以前一样传递参数
        //坏处是，由于线程用完会回到线程池，还可以被调用，有数据泄露的风险，所以需要销毁线程
        UserThreadLocal.set(userId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
